package com.wing.wcabinet.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.user.feign.UserClient;
import com.wing.wcabinet.model.entity.WauthorityManage;
import com.wing.wcabinet.model.entity.WauthorityMember;
import com.wing.wcabinet.model.request.WauthorityMemberForm;
import com.wing.wcabinet.service.WauthorityManageService;
import com.wing.wcabinet.service.WauthorityMemberService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-权限组成员表管理", tags = "#/wcabinet/wauthorityMember")
@RestController("wauthorityMemberController")
@RequestMapping("wcabinet/admin/wauthorityMember")
@RequiredArgsConstructor
public class WauthorityMemberController {

    private final WauthorityMemberService authorityMemberService;

    private final UserClient userClient;
    private final WauthorityManageService authorityManageService;

    @ApiOperation(value = "查询所有权限组成员", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<WauthorityMember> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String authorityManageId
            ,String userName
    ){

        Page<WauthorityMember> pg = new Page<>(page, limit);
        QueryWrapper<WauthorityMember> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }

        if(StringUtils.isNotBlank(authorityManageId)){
            queryWrapper.eq("authority_manage_id",authorityManageId);
        }
        if(StringUtils.isNotBlank(userName)){
            queryWrapper.eq("user_name",userName);
        }

        IPage<WauthorityMember> list = authorityMemberService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加权限组成员", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(WauthorityMemberForm.Add.class) WauthorityMemberForm authorityMemberForm) {
        if (authorityMemberService.add(authorityMemberForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "批量添加权限组成员", notes = "添加")
    @PostMapping("/addBatch")
    public JsonResult addBatch(@RequestBody List<WauthorityMemberForm> authorityMemberFormList) {
        if (authorityMemberService.addBatch(authorityMemberFormList) == authorityMemberFormList.size()) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    @ApiOperation(value = "修改权限组成员", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(WauthorityMemberForm.Update.class) WauthorityMemberForm authorityMemberForm) {
        WauthorityMember authorityMember = authorityMemberService.getById(authorityMemberForm.getId());
        if(authorityMember == null){
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(WauthorityMember.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(authorityMemberForm, authorityMember, copyOptions);
        if (authorityMemberService.updateById(authorityMember)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除权限组成员", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorityMemberId", value = "权限组成员表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long authorityMemberId) {
        if (authorityMemberService.deleteAuthorityMemberById(authorityMemberId)>0) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "批量删除权限组成员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true, dataType = "Long", paramType = "path")
    })
    @DeleteMapping("/batchIds")
    public JsonResult batchDelete(@RequestParam("ids[]") Long[] ids) {
        if (authorityMemberService.batchDeleteAuthorityMemberById(ids) > 0) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    /**
     * 根据用户id返回用户信息 加上柜子id 同个柜子只能在一个权限组
     */
    @GetMapping("/getAuthorityMemberByUserId")
    public JsonResult getAuthorityMemberByUserId(@RequestParam("id")Long id,@RequestParam("cabinetId")Long cabinetId){
        //该柜子在的权限组
        List<WauthorityManage> authorityManageList = authorityManageService.list(new LambdaQueryWrapper<WauthorityManage>().eq(WauthorityManage::getCabinetId,cabinetId));
        for (WauthorityManage authorityManage:authorityManageList){
            List<WauthorityMember> list = authorityMemberService.list(new LambdaQueryWrapper<WauthorityMember>().eq(WauthorityMember::getUserId, id).eq(WauthorityMember::getAuthorityManageId,authorityManage.getId()));
            if(list.size()>0){
                return JsonResult.fail("该员工已存在于其他权限组，请移除后再添加");
            }
        }
        return JsonResult.success(userClient.getUserInfo(id));
    }

}
